function [out ] = cross_valid(X,Y,NCV,flow_function,varargin)

    %  Constants
    NTrial = size(X,3);
    NTrialTest = fix(NTrial/NCV);
    out = zeros(size(X,3),1);
    
    %cross validation
    for iCV = 1:NCV 

        idxTest = 1+(iCV-1)*NTrialTest:iCV*NTrialTest;
        if iCV ==NCV
            idxTest = 1+(iCV-1)*NTrialTest:NTrial;
        end
        idxTraining = 1:NTrial;
        idxTraining(idxTest)=[];

        if isempty(varargin)
            Ytest = flow_function(X(:,:,idxTest),X(:,:,idxTraining),Y(idxTraining));
        else
            Ytest = flow_function(X(:,:,idxTest),X(:,:,idxTraining),Y(idxTraining),varargin{:});
        end
        out(idxTest) = Ytest;

    end